<template>

  <a-modal
    v-model:visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="null"
    :width="400"
  >

    <!-- 内容展示 -->
    <template #title>
      <a-row :wrap="false">
        <div class="title-bar">
          <img src="../assets/coffee_logo.png" alt="logo" class="logo">
        </div>
      </a-row>
      <a-row>
        <h1 style="text-align: center; margin: 30px 0 24px 0; font-size: 24px; font-weight: 500;">用户登录</h1>
      </a-row>
    </template>

    <!-- 表单 -->
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >

      <!-- 手机号 -->
      <a-form-item
        label="手机号"
        name="phone"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
        ]"
      >
        <div style="display: flex; gap: 8px; width: 240px;">
          <a-input v-model:value="formState.phone" placeholder="请输入手机号" style="flex: 1"/>
        </div>
      </a-form-item>

      <!-- 验证码 -->
      <a-form-item
        label="验证码"
        name="verifyCode"
        :rules="[{ required: true, message: '请输入验证码' }]"
      >
        <div style="display: flex; gap: 8px; width: 240px;">
          <a-input v-model:value="formState.verifyCode" placeholder="请输入验证码" style="flex: 1"/>
          <a-button
            :disabled="countdown > 0"
            @click="handleGetCode"
          >
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </a-button>
        </div>
      </a-form-item>

      <!-- 登录按钮 -->
      <a-form-item :wrapper-col="{ offset: 5, span: 19 }">
        <a-button type="primary" html-type="submit" @click="onHandleSubmit(formState)">登录</a-button>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { userLogin } from "@/api/user";
import { useLoginStore } from "@/store/useLoginUserStore";
import { message, Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import { getVerificationCode } from "@/api/sms";

const loginStore = useLoginStore();
const countdown = ref(0);
const visible = ref(false);

interface FormState {
  phone: string;
  verifyCode: string;
}

const formState = reactive<FormState>({
  phone: '',
  verifyCode: '',
});

const handleGetCode = async () => {
  if (!formState.phone) {
    message.error('请先输入手机号');
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(formState.phone)) {
    message.error('请输入正确的手机号');
    return;
  }

  try {
    const res = await getVerificationCode(formState.phone);
    if (res.data.code === 200 && res.data.data) {
      Modal.success({
        title: '验证码',
        content: `您的验证码是：${res.data.data.code}`,
        okText: '我知道了'
      });
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      message.error(res.data.msg || '获取验证码失败');
    }
  } catch (error) {
    message.error('获取验证码失败');
  }
};

const onHandleSubmit = async (values: FormState) => {

  try {
    const loginParams = {
      phone: values.phone,
      verifyCode: Number(values.verifyCode)
    };

    const res = await userLogin(loginParams);
    if(res.data.code === 200 && res.data.data){
      localStorage.setItem('token', res.data.data.token);
      message.success("登录成功");
      visible.value = false;

      try {
        await loginStore.fetchLoginUser();
      } catch (error) {
        console.error('获取用户信息失败:', error);
        message.error("获取用户信息失败，请刷新页面重试");
      }
    } else {
      message.error(res.data.msg || "登录失败");
    }
  } catch (error) {
    console.error('登录失败:', error);
    message.error("登录失败，请稍后重试");
  }
};

const onFinish = (info: any) => {};
const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const handleOk = () => {
  visible.value = false;
};

const handleCancel = () => {
  visible.value = false;
};

// 暴露方法给父组件
defineExpose({
  show: () => {
    visible.value = true;
  }
});

</script>
